package edu.fudan.cse.medlab.event.moresite;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Vector;


public class HostManager {
	Vector<String> hostlist;
	Vector<Integer> score;
	String file;
	public HostManager(String file){
		hostlist = new Vector<String>();
		score = new Vector<Integer>();
		this.file = file;
	}
	
	public boolean add(String s){
		if(hostlist.contains(s)){
			int k = hostlist.indexOf(s);
			Integer n = score.get(k);
			score.set(k, n+1);
			return false;
		}
		else{
			hostlist.add(s);
			score.add(1);
			return false;
		}
	}
	
	public void sort(){
		Integer ti = new Integer(0);
		String ts = new String("");
		for (int i = 0; i < score.size(); i++) {
			for (int j = 0; j < score.size()-i-1; j++) {
				if(score.elementAt(j)<score.elementAt(j+1)){
					ti = score.elementAt(j+1);
					score.setElementAt(score.elementAt(j),j+1);
					score.setElementAt(ti,j);
					ts = hostlist.elementAt(j+1);
					hostlist.setElementAt(hostlist.elementAt(j),j+1);
					hostlist.setElementAt(ts,j);
				}
			}
		}
	}
	
	public void readFromFile(){
		try{
			BufferedReader bin=new BufferedReader(new FileReader(file));
			String s;
			int k;
			while((s = bin.readLine())!=null){
				k = s.indexOf(":");
				hostlist.add(s.substring(0,k));
				score.add(Integer.parseInt(s.substring(k+1,s.length())));
			}
			System.out.println(hostlist.toString());
			System.out.println(score.toString());
			bin.close();
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
	
	
	public void writeToFile(){
		try{
			System.out.println(hostlist.toString());
			System.out.println(score.toString());
			BufferedWriter bout=new BufferedWriter(new FileWriter(file));
			for (int i = 0; i < hostlist.size(); i++) {
				bout.write(hostlist.get(i) +":"+score.get(i)+ "\r\n");
				bout.flush();
			}
			bout.close();
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
	
	
	public static void main(String[] args){
		HostManager hm = new HostManager("hostmanager.txt");
		hm.readFromFile();
		hm.sort();
		hm.writeToFile();
	}
	
	

}
